/**
 * Created by luckyjing on 15/12/28.
 */
var mysql = require('mysql');
var $conf = require('../conf/db');
var $sql = require('./sqlMapping');
//创建连接池
var pool = mysql.createPool($conf.mysql);
module.exports = {
    get: function (req, res, next) {
        var params = req.params;
        pool.getConnection(function (err, connection) {
            if (err) {
                writeError(err);
            } else {
                connection.query($sql.queryById, [params], function (err, result) {
                    if (err) {
                        writeError();
                    } else {
                        res.json(result)
                    }
                })
            }
            connection.release();
        });
    },
    add: function (req, res, next) {
        var params = req.body;
        pool.getConnection(function (err, connection) {
            if(err){
                writeError(res,err);
            }else{
                connection.query($sql.insert,[params.name,params.age], function (err, result) {
                    if(err){
                        writeError(res,err);
                    }else{
                        res.json({
                            code:200,
                            msg:"增添成功"
                        });
                    }
                });
                connection.release();
            }
        });
    }
};
function writeError(res,err){
    res.json({
        result: 'error',
        err: err.code
    });
}